package com.portal.admin.base.interceptor;

import com.portal.admin.base.exception.SessionException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    /**
     * 登录session key
     */
    public final static String SESSION_KEY = "token";

    @Bean
    public SecurityInterceptor getSecurityInterceptor() {
        return new SecurityInterceptor();
    }

    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration addInterceptor = registry.addInterceptor(getSecurityInterceptor());
        // 接口排除配置
        addInterceptor.excludePathPatterns("/api/login/**");
        // web排除配置
        addInterceptor.excludePathPatterns("/admin/login/**");
        addInterceptor.excludePathPatterns("/admin/sys/**");
        // 拦截配置
        addInterceptor.addPathPatterns("/admin/**");
        addInterceptor.addPathPatterns("/api/**");
    }

    //拦截器
    private class SecurityInterceptor extends HandlerInterceptorAdapter {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
            if (request.getSession(false) == null) {
                throw new SessionException("Session has been invalidated!");
            } else {
                return true;
            }
        }
    }
}